package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;
    /**
     * 发表评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        //判断用户是否登录
        //获取线程里的user
        User user = AppThreadLocalUtil.get();
        if (user == null || (!StringUtils.isEmpty(user.getUserId())&&user.getUserId().equals(0))){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断评论内容是否大于140字
        if (dto == null ||dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // TODO: 2022/6/28  阿里云内容安全审核评论
        Boolean flag = checkText(dto.getContent());
        if (!flag) return ResponseResult.errorResult(500,"评论内容违规");
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getUserId());
        //远程调用feign根据user_id查询出用户名
        ResponseResult<ApUser> result = userFeign.getById(user.getUserId());
        apCommentRepay.setAuthorName(result.getData().getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        //保存评论回复
        mongoTemplate.save(apCommentRepay);
        //评论的的回复数+1
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(query,update, ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 内容审查
     * @param content
     * @return
     */
    private Boolean checkText(String content) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(content);
            //检测后返回的结果判断
            String suggestion = (String) map.get("suggestion");
            if ("pass".equals(suggestion)) {
                //审核通过
                flag = true;
            }else {
                flag =false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 加载评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        //判断用户是否登录
        //获取线程里的user
        User user = AppThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //构建回复点赞记录
        ApCommentRepayLike repayLike = new ApCommentRepayLike();
        repayLike.setAuthorId(user.getUserId());
        repayLike.setCommentRepayId(dto.getCommentRepayId());
        repayLike.setOperation(dto.getOperation());
        //判断当前用户在当前评论回复有无点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()))
                .addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one == null){
            //没有点赞记录
            mongoTemplate.save(repayLike);
            //更新回复的点赞数 +1
            Query repayQuery = new Query();
            repayQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(repayQuery ,update,ApCommentRepay.class);
        }else {
            //有过点赞记录
            if (dto.getOperation() != one.getOperation()){
                //判断当前是点赞还是取消点赞
                int add = 1;
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                if (dto.getOperation() == 1){
                    //取消点赞
                    add = -1;
                }
                //更新该回复点赞总数量
                Query repayQuery = new Query();
                repayQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
                Update update = new Update();
                update.inc("likes",add);
                mongoTemplate.updateFirst(repayQuery,update,ApCommentRepay.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 加载回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {

        //给一个默认的每页展示大小
        if (dto.getSize()==null || dto.getSize()<=0 ||dto.getSize()>50){
            dto.setSize(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        Pageable page = PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"likes");
        query.with(page);
        List<ApCommentRepay> repays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断用户是否登录
        //获取线程里的user
        User user = AppThreadLocalUtil.get();
        List<ApCommentRepayLike> repayLikes = new ArrayList<>();
        if (user != null){
            //拿到当前评论的所有评论回复id -->repayIds
            List<String> repayIds = new ArrayList<>();
            for (ApCommentRepay repay : repays) {
                repayIds.add(repay.getId());
            }
            //查询当前评论,当前用户点赞的评论回复
            Query likeQuery = new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentRepayId").in(repayIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            repayLikes = mongoTemplate.find(likeQuery, ApCommentRepayLike.class);
        }
        //取出当前评论,当前用户点赞的评论回复
        List<String> repayLikesIds = new ArrayList<>();
        for (ApCommentRepayLike repayLike : repayLikes) {
            repayLikesIds.add(repayLike.getCommentRepayId());
        }
        //返回vo集合对象
        List<ApCommentRepayVo> vos = new ArrayList<>();
        for (ApCommentRepay repay : repays) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(repay,vo);
            //默认没有点赞  设置为1
            vo.setOperation(1);
            if (repayLikesIds.contains(repay.getId())){
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }
}
